import { defHttp } from '/@/utils/http/axios';
import { ItemMenu } from '../model/sys/menuModel';
import { eachTree, filter, listToTree } from '/@/utils/helper/treeHelper';
import { isArray } from '/@/utils/is';
import { createSessionStorage } from '/@/utils/cache';

export enum Api {
  GetMenuList = '/sys/menu/list',
}
/**
 * 静态菜单，不验证权限
 */
const staticMenu: ItemMenu[] = [
  {
    id: -1,
    icon: '',
    type: 1,
    parentId: null,
    title: '关于',
    router: '/sys/about',
    viewPath: '/sys/about/index',
    isShow: true,
  },
];

/**
 *
 * @returns 获取则边栏菜单
 */
export const getMenuList = async () => {
  const menus = await defHttp.post<ItemMenu[]>({ url: Api.GetMenuList });
  //获取并储权限节点
  const nodes = getNodes(menus);
  createSessionStorage().set('auth_nodes', nodes);
  //console.log('menus', menus)
  for (let i = 0; i < menus.length; i++) {
    if (menus[i].isShow == false) menus.splice(i, 1);
  }
  menus.push(...staticMenu);
  const routes = listToTree(menus, { pid: 'parentId' });

  //过滤权限结点菜单
  const _menus = filter(
    routes,
    (item) => {
      return item.type < 2 ? true : false;
    },
    { pid: 'parentId' },
  );
  // console.log('_menus::', _menus);
  eachTree(_menus, (route, parentRoute) => {
    route.path = route.router;
    route.meta = { title: route.title, icon: route.icon, ignoreKeepAlive: !route.keepalive };
    route.component = route.viewPath;
    if (!route.name) route.name = route.router.replace(/^\//, '');
    if (parentRoute.name) route.name = parentRoute.name + '_' + route.name;
    if (!route.parnetId && route.type == 0) route.component = 'LAYOUT';
    return route;
  });
  return _menus;
};

function getNodes(menus: any[]) {
  return menus
    .filter((item) => item.type == 2 && isArray(item.nodes))
    .map((item) =>
      item.nodes
        .map((item) => {
          const method = item.pop();
          return `/${item.join('/')}${method.indexOf(' ') > 0 ? '/' + method : method}`;
        })
        .join(''),
    );
}
